package com.lucifer.d.security.service.local.aspect;

import com.lucifer.d.security.exception.TokenException;
import com.lucifer.d.security.model.SecurityConfigModel;
import com.lucifer.d.security.transfer.SignTransfer;
import com.lucifer.d.util.StringUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author Lucifer
 * @create 2024 - 07 - 17 14:28
 */
@Aspect
public class SignAspect {

    @Autowired
    private SignTransfer signTransfer;

    @Autowired
    private SecurityConfigModel securityConfigModel;

    /**
     * 定义切入点，为所有方法
     */
    @Pointcut("@annotation(com.lucifer.d.security.annotation.verify.Sign)")
    public void signAspectMethod() {}

    /**
     * 定义切入点，为所有service
     */
    @Pointcut("@within(com.lucifer.d.security.annotation.verify.Sign)")
    public void signAspectClass() {}

    /**
     * 切入点前置执行内容
     *
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("signAspectClass() || signAspectMethod()")
    public Object doBefore(ProceedingJoinPoint point) throws Throwable {
        // 获取request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (StringUtil.isEmpty(request.getHeader(securityConfigModel.getSignHead()))){
            throw new TokenException(TokenException.CODE302);
        }
        if (signTransfer.getSecurityUser() == null){
            throw new TokenException(TokenException.CODE303);
        }
        return point.proceed();
    }

}
